<?php 
class DB_Functions {
	private $db;
	
	function __construct(){
		require_once __DIR__ . '/db_connect.php';
		$this->db = new DB_CONNECT();
		$this->db->connect();
	}
	function __destruct(){}
	
	/**
	 * Storing new user
	 * return user details
	 */
	public function storeUser($name, $email, $password, $gcm_regid){
		$uid = uniqid('', true);
		$hash = $this->hashSSHA($password);
		$encrypted_password = $hash["encrypted"]; // encrypted password
        $salt = $hash["salt"]; // salt
		
		$result = mysql_query("INSERT INTO USERS(unique_id, name, email, encrypted_password, salt, gcm_regid)
				 VALUES('$uid', '$name', '$email', '$encrypted_password', '$salt', '$gcm_regid' )");
		if($result){
			$id = mysql_insert_id();
			$result = mysql_query("SELECT * FROM USERS WHERE id = $id");
			return mysql_fetch_array($result);
		} else {
			return false;
		}
	}
	
	/**
	 * Get user by email and password
	 */
	public function getUserByEmailAndPassword($email, $password){
		$result = mysql_query("SELECT * FROM USERS WHERE email = '$email'") or die(mysql_error());
		$no_of_rows = mysql_num_rows($result);
		if($no_of_rows > 0){
			$result = mysql_fetch_array($result);
			$salt = $result['salt'];
			$encrypted_password = $result['encrypted_password'];
			$hash = $this->checkhashSSHA($salt, $password);
			// check for password equality
			if ($encrypted_password == $hash) {
				// user authentication details are correct
				return $result;
			}  else {
            // user not found
            	return false;
        	}
		}
	}
	/**
	 * Check user is existed or not
	 */
	public function isUserExisted($email){
		$result = mysql_query("SELECT email from USERS WHERE email = '$email'");
		$no_of_rows = mysql_num_rows($result);
		if ($no_of_rows > 0) {
			// user existed
			return true;
		} else {
			// user not existed
			return false;
		}
	}
	/**
	 * Encrypting password
	 * @param password
	 * returns salt and encrypted password
	 */
	public function hashSSHA($password){
		$salt = sha1(rand());
		$salt = substr($salt, 0, 10);
		$encrypted = base64_encode(sha1($password . $salt, true) . $salt);
		$hash = array("salt" => $salt, "encrypted" => $encrypted);
		return $hash;
	}
	/**
	 * Decrypting password
	 * @param salt, password
	 * returns hash string
	 */
	public function checkhashSSHA($salt, $password) {
	
		$hash = base64_encode(sha1($password . $salt, true) . $salt);
	
		return $hash;
	}
}
?>